<script setup lang="ts">
import { onMounted, ref, onUnmounted, watch } from 'vue';
import * as echarts from 'echarts';
import { updateConfig } from '../testChart/size'

const chartRef = ref<HTMLElement | null>(null);
let myChart: echarts.ECharts | null = null;
// 获取屏幕宽度
const screenWidth = ref(window.innerWidth);
const chartOption = ref(updateConfig(screenWidth.value));

onMounted(() => {
  if(window.innerWidth > 666) {
    chartInit();
    window.addEventListener('screenWidth', handleScreenWidth);
    window.addEventListener('resize', handleResize);
  }
});
onUnmounted(() => {
    window.removeEventListener('screenWidth', handleScreenWidth);
    window.removeEventListener('resize', handleResize);
    // 销毁图表实例
    myChart?.dispose();
    myChart = null;
});

// 监听窗口大小变化的处理函数
const handleScreenWidth = () => {
  screenWidth.value = window.innerWidth;
};
// 窗口大小变化时重绘图表
const handleResize = () => { myChart?.resize(); };
// 初始化图表
const chartInit = () => {
    if (chartRef.value) {
        // 基于准备好的dom，初始化echarts实例
        myChart = echarts.init(chartRef.value);
        // 绘制图表
        myChart.setOption(chartOption.value);
    }
};
// 监听宽度变化重绘图表
watch(screenWidth,(newVal, oldVal) => {
    if(newVal < 800) {
        // console.log("屏幕尺寸小于1450");
        chartInit();
    }
})
// 使用watch监听screenWidth的变化
watch(
  () => screenWidth.value, // 监听源
  (newWidth, oldWidth) => {
    // 当新宽度小于800px时打印信息
    if (newWidth < 800) {
      // console.log(`屏幕宽度小于800px: 当前宽度为${newWidth}px`);
      // console.log(`宽度变化: 从${oldWidth}px变为${newWidth}px`);
    }
  },
  {
    immediate: true // 初始化时立即执行一次检查
  }
);

</script>

<template>
    <div ref="chartRef" class="container"></div>
</template>

<style lang="scss" scoped>
.container {
    width: 100%;
    height: 300px;
}

@media (max-width: 1432px) {
    .container {
        width: 100%;
        height: 240px;
    }
}
</style>